//
//  SongListViewController.m
//  MooreDoll
//
//  Created by Joe on 2014/12/4.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "SongListViewController.h"
#import <AudioToolbox/AudioConverter.h>
#include "libxclient.h"
#include "lame.h"
@interface SongListViewController ()

@end

@implementation SongListViewController
@synthesize Array_song,musicPlayer,chatRoom;


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //一個監聽事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMusic:) name:@"playSong" object:nil];
    
    //存放歌曲的陣列
    Array_song = [[NSMutableArray alloc] init];
    
    // 取得所有歌曲資訊
    // MPMediaItemCollection是該首歌曲的集合，MPMediaItem則是該首歌曲的資訊
    // 播放音樂需套用query或者是 MPMediaItemCollection
    // 每筆Cell需儲存的peroperty有: MPMediaItemCollection、item.title、item.url、MPMediaItemPropertyPlaybackDuration
    MPMediaQuery    *songQuery   = [MPMediaQuery songsQuery];
    NSArray         *queryResult = [songQuery collections];
    
    for (MPMediaItemCollection *collection in queryResult)
    {
        for (id item in collection.items)
        {
            
            if ([item isKindOfClass:[MPMediaItem class]])
            {
                MPMediaItem *mediaItem = (MPMediaItem *)item;
                NSURL *url = [mediaItem valueForProperty:MPMediaItemPropertyAssetURL];
                
                // 確認音樂是否存在，有些音樂是iTune的link，url可判斷是否為real path
                if (url)
                {
                    SongInfo *info = [[SongInfo alloc] initWithCollection:collection
                                                                    Title:mediaItem.title
                                                                     Time:mediaItem.playbackDuration
                                                                  andPath:[mediaItem valueForProperty:MPMediaItemPropertyAssetURL]
                                                             andMusicItem:mediaItem];
                    [Array_song addObject:info];
                }

            }
            
        }
    }
    nowTrack = (int)Array_song.count +1;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (musicPlayer) {
        [musicPlayer stop];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"playSong" object:nil];
}
-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"playSong" object:nil];
}
-(void)playMusic:(NSNotification * )info
{
    //音樂播放btn press
    NSDictionary *dic = [info object];
    MPMediaItemCollection *collection = [dic objectForKey:@"collection"];
    int buttonTrack =[(NSString *)[dic objectForKey:@"buttonIndex"] intValue];
    
    if (!musicPlayer)
        musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
    
    if (nowTrack == buttonTrack) {
        [musicPlayer stop];
        
        nowTrack = (int)Array_song.count +1;
        //list無播放
    }
    else{
        [musicPlayer setQueueWithItemCollection:collection];
        [musicPlayer play];
        nowTrack = buttonTrack;
    }
    
    
}

-(IBAction)okButtonPress:(id)sender
{
    
    if (assetURL == nil || selectedSong == nil)
    {
        return;
    }
    

    [self.delegate sendMusicWithMediaItem:selectedSong];
    [self.navigationController popViewControllerAnimated:NO];

}


-(IBAction)cancelButtonPress:(id)sender
{
    dispatch_async(dispatch_get_main_queue(),
    ^{
        [self.navigationController popToRootViewControllerAnimated:NO];
    });
}


#pragma mark TableViewDelegate
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return Array_song.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    SongListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" ];
    
    if (cell == nil)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SongListCell" owner:self options:nil] objectAtIndex:0];
        SongInfo *info = [Array_song objectAtIndex:indexPath.row];
        
        //將秒數轉為時間格式
        float during = info.songDuring / (float)60;
        NSString *duringString = [NSString stringWithFormat:@"%1.2f",during];
        NSRange dotLocate = [duringString rangeOfString:@"."];
        duringString = [duringString stringByReplacingCharactersInRange:dotLocate withString:@":"];
        
        cell.LB_songName.text = info.NS_songName;
        cell.LB_songDuring.text = [NSString stringWithFormat:@"%@",duringString];
        cell.buttonIndex = (int)indexPath.row;
        cell.collection = info.collection_song;
        
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 79;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    selectedSong = ((SongInfo *)[Array_song objectAtIndex:indexPath.row]).item_song;
    assetURL = [selectedSong valueForProperty:MPMediaItemPropertyAssetURL];
    
}




@end
